package dyyx.client.echo;

import java.time.LocalTime;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class EchoClient {

	private static String host = "127.0.0.1";
	private static int port = 6789;

	public static void main(String[] args) throws Exception{

		EchoClient client = new EchoClient();
		ChannelFuture channelFuture = client.start();
		
		System.out.println("client="+client);
		System.out.println("channelFuture="+channelFuture);

		
		while(true){
			Thread.sleep(3000);
			System.out.println(LocalTime.now());
			// channelFuture.channel().writeAndFlush("clientmsg at "+LocalTime.now());
		}
		
		
	}

	private ChannelFuture start() throws Exception{

		NioEventLoopGroup nelg = new NioEventLoopGroup();
		

			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(nelg)
			.channel(NioSocketChannel.class)
			.remoteAddress(host, port)
			.handler(new ChannelInitializer<Channel>() {

					@Override
					protected void initChannel(Channel ch) throws Exception {
						ch.pipeline().addLast("framer",
								new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
						ch.pipeline().addLast("decoder", new StringDecoder());
						ch.pipeline().addLast("encoder", new StringEncoder());
						ch.pipeline().addLast(new EchoClientHandler());
					}
				});
			ChannelFuture channelFuture = bootstrap.connect().sync();
			return channelFuture;
			// ChannelFuture future = bootstrap.connect().sync();
			// future.channel().closeFuture().sync();

		
	}	
	
	
	//  
	
	

	
}
